import React, { Component } from 'react';

/**
 * memorize state
 * store the wrapped components when state changed
 * how to use:
 * 1. uing this component as HOC in target component
 * 2. call this.props.memorize(this.state) in component did update method
 * 3. in wrapped component's component will mount method, 
 *    set "memory"'s data into state
 */

 const GLOBAL_PAGE_MEMORIZED_STATE_KEY = 'page-memorized-state';

export default (config={}) => WrappedComponent => {
  class MemorizedState extends Component {
    memory = {}

    componentWillMount() {
      let cacheData = JSON.parse(localStorage.getItem(GLOBAL_PAGE_MEMORIZED_STATE_KEY)) || {};
      this.memory = cacheData[this.props.match.path] || {};
    }

    clearMemorized = () => {
      this.memory = {};
      let cacheData = JSON.parse(localStorage.getItem(GLOBAL_PAGE_MEMORIZED_STATE_KEY)) || {};
      cacheData[this.props.match.path] = this.memory;
      localStorage.setItem(GLOBAL_PAGE_MEMORIZED_STATE_KEY, JSON.stringify(cacheData));
    }

    memorize = (state) => {
      try {
        let data = {...state};
        config.ignore && config.ignore.forEach(key => {
          delete data[key];
        });
        this.memory = data;
        let cacheData = JSON.parse(localStorage.getItem(GLOBAL_PAGE_MEMORIZED_STATE_KEY)) || {};
        cacheData[this.props.match.path] = this.memory;
        localStorage.setItem(GLOBAL_PAGE_MEMORIZED_STATE_KEY, JSON.stringify(cacheData));
      }
      catch (e) {
        console.log(e);
      }
    }

    render() {
      return <WrappedComponent {...this.props} memory={this.memory} memorize={this.memorize} clearMemorized={this.clearMemorized} />
    }
  }

  return MemorizedState;
};